package com.twang.stock.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.twang.stock.entity.*;
import com.twang.stock.entity.ex.BanKuaiStockInfo;
import com.twang.stock.entity.ex.LongHuInfoEx;
import com.twang.stock.entity.ex.LongHuInfoXiWeiEx;
import com.twang.stock.mapper.CompanyStockMinutesMapper;
import com.twang.stock.mapper.HotTagMapper;
import com.twang.stock.redis.RedisUtil;
import com.twang.stock.service.BanKuaiService;
import com.twang.stock.service.LongHuBangService;
import com.twang.stock.service.jinyan.CommonService;
import com.twang.stock.threadPool.AsycTaskExecutorConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.ModelAndView;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * 概念板块信息
 */
@Service
@Slf4j
public class BanKuaiServiceImpl implements BanKuaiService {

    @Autowired
    private CommonService commonService;

    @Resource
    private CompanyStockMinutesMapper companyStockMinutesMapper;


    @Autowired
    private LongHuBangService longHuBangService;

    @Resource
    private HotTagMapper hotTagMapper;

    @Autowired
    private RedisUtil redisUtil;


    private static int DEFAULT_VALUE_亿=100000000;
    private static int DEFAULT_VALUE_千万=10000000;
    private static int DEFAULT_VALUE_百万=1000000;

    @Autowired
    private AsycTaskExecutorConfig asycTaskExecutorConfig;

    @Override
    public void 板块主页(ModelAndView modelAndView) throws InterruptedException {
        List<String> keyList = Lists.newArrayList(CommonService.AI_COMPUTING_SERVER, CommonService.AI_CPO, CommonService.AI_DATA, CommonService.BK_1, CommonService.BK_2, CommonService.BK_3, CommonService.BK_4, CommonService.BK_5, CommonService.BK_6);
        final CountDownLatch latch = new CountDownLatch(9);
        for (String str : keyList) {
            asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                try {
                    //AI_COMPUTING_SERVER
                    modelAndView.addObject(str, listByType(str));
                    BaseCommon baseCommon = commonService.getBaseCommon(str);
                    modelAndView.addObject(str + "_NAME", baseCommon.getCommonDesc());
                    modelAndView.addObject(str + "_KEY", baseCommon.getCommonKey());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    log.info("gptGaiNian 剩余条数:{}", latch.getCount());
                    latch.countDown();
                }
            });
        }
        modelAndView.addObject("keyList", keyList);
        latch.await();
    }

    public void getStockListByBanKuai(String bkName){

    }


    /**
     * @param modelAndView
     * @throws InterruptedException
     */
    @Override
    public void 龙虎榜(ModelAndView modelAndView) throws InterruptedException {
        List<LongHuInfoEx> result = Lists.newArrayList();
        LongHuInfo param=new LongHuInfo();
        List<LongHuInfo> list = longHuBangService.query(param);
        list.stream().forEach(item -> {
            LongHuInfoEx longHuInfoEx = new LongHuInfoEx();
            BeanUtils.copyProperties(item, longHuInfoEx);
            LongHuInfoXiWei xiweiParam = new LongHuInfoXiWei();
            xiweiParam.setLongHuId(item.getId());
            List<LongHuInfoXiWei> dealList = longHuBangService.queryLongXiWei(xiweiParam);
            List<String> buyTag = Lists.newArrayList();//主买
            List<String> saleTag = Lists.newArrayList();//主卖
            List<LongHuInfoXiWeiEx> xiwei = dealList(dealList, buyTag, saleTag);
            longHuInfoEx.setBuyTag(buyTag);
            longHuInfoEx.setSaleTag(saleTag);
            /** 买入前五 */
            LongHuInfoXiWei 买一 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 1 && xw.getBuyOrSale().equals("buy")).collect(Collectors.toList()));
            LongHuInfoXiWei 买二 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 2 && xw.getBuyOrSale().equals("buy")).collect(Collectors.toList()));
            LongHuInfoXiWei 买三 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 3 && xw.getBuyOrSale().equals("buy")).collect(Collectors.toList()));
            LongHuInfoXiWei 买四 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 4 && xw.getBuyOrSale().equals("buy")).collect(Collectors.toList()));
            LongHuInfoXiWei 买五 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 5 && xw.getBuyOrSale().equals("buy")).collect(Collectors.toList()));
            longHuInfoEx.setMrOne(买一);
            longHuInfoEx.setMrSecond(买二);
            longHuInfoEx.setMrThree(买三);
            longHuInfoEx.setMrFour(买四);
            longHuInfoEx.setMrFive(买五);
            /** 卖出前五 */
            LongHuInfoXiWei 卖一 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 1 && xw.getBuyOrSale().equals("sale")).collect(Collectors.toList()));
            LongHuInfoXiWei 卖二 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 2 && xw.getBuyOrSale().equals("sale")).collect(Collectors.toList()));
            LongHuInfoXiWei 卖三 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 3 && xw.getBuyOrSale().equals("sale")).collect(Collectors.toList()));
            LongHuInfoXiWei 卖四 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 4 && xw.getBuyOrSale().equals("sale")).collect(Collectors.toList()));
            LongHuInfoXiWei 卖五 = getLongHuInfoXiWei(xiwei.stream().filter(xw -> xw.getXiWeiRow().intValue() == 5 && xw.getBuyOrSale().equals("sale")).collect(Collectors.toList()));
            longHuInfoEx.setMcOne(卖一);
            longHuInfoEx.setMcSecond(卖二);
            longHuInfoEx.setMcThree(卖三);
            longHuInfoEx.setMcFour(卖四);
            longHuInfoEx.setMcFive(卖五);
            result.add(longHuInfoEx);
        });
        modelAndView.addObject("list", result);
    }

    @Override
    public void 龙虎榜列表(ModelAndView modelAndView) throws InterruptedException {
        List<LongHuInfoEx> result = Lists.newArrayList();

        LongHuInfo param=new LongHuInfo();
        List<LongHuInfo> list = longHuBangService.query(param);
        list.stream().forEach(item -> {
            LongHuInfoEx longHuInfoEx = new LongHuInfoEx();
            BeanUtils.copyProperties(item, longHuInfoEx);
            LongHuInfoXiWei xiweiParam = new LongHuInfoXiWei();
            xiweiParam.setLongHuId(item.getId());
            List<LongHuInfoXiWei> dealList = longHuBangService.queryLongXiWei(xiweiParam);
            List<String> buyTag = Lists.newArrayList();//主买
            List<String> saleTag = Lists.newArrayList();//主卖
            List<LongHuInfoXiWeiEx> xiwei = dealList(dealList, buyTag, saleTag);
            longHuInfoEx.setBuyTag(buyTag);
            longHuInfoEx.setSaleTag(saleTag);
            result.add(longHuInfoEx);
        });
        modelAndView.addObject("list", list);
    }


    @Override
    public  List<BanKuaiStockInfo>  listByType(String typeKey) {
        List<BanKuaiStockInfo> banKuaiStockInfoList = Lists.newArrayList();
        String key = "BanKuaiStockInfo-listByType-" + typeKey;
        Object obj = redisUtil.get(key);
        if (null == obj) {
            String data = commonService.getValue(typeKey);
            String[] codes = data.split(",");
            for (int i = 0; i < codes.length; i++) {
                //初始化信息
                BanKuaiStockInfo banKuaiStockInfo = new BanKuaiStockInfo();
                banKuaiStockInfo.setCompanyCode(codes[i]);
                CompanyStockMinutes companyStockMinutes = companyStockMinutesMapper.queryByCode(codes[i]);
                if (null == companyStockMinutes) {
                    log.error("companyStockMinutes is null company_code={}", codes[i]);
                }
                BeanUtils.copyProperties(companyStockMinutes, banKuaiStockInfo);
                //
                List<CompanyStockMinutes> list = companyStockMinutesMapper.queryYesterDayAndToday(companyStockMinutes.getCompanyCode(), "1000");
                if (!CollectionUtils.isEmpty(list) || list.size() >=2) {
                    banKuaiStockInfo.setYesterDay30MinVol(初始化单位(list.get(1).getTradeVol()).replace("万", "").replace("亿", ""));
                    banKuaiStockInfo.setToDay30MinVol(初始化单位(list.get(0).getTradeVol()).replace("万", "").replace("亿", ""));
                }

                banKuaiStockInfo.setTodayChengJiaoE(初始化单位(companyStockMinutes.getTradeSum()));
                banKuaiStockInfoList.add(banKuaiStockInfo);
            }
            redisUtil.set(key, JSONObject.toJSONString(banKuaiStockInfoList));
        } else {
            banKuaiStockInfoList = JSONObject.parseArray(obj.toString(), BanKuaiStockInfo.class);
        }
        return banKuaiStockInfoList;
    }


    private String 初始化单位(BigDecimal value){
        String str="";
        if (value.compareTo(new BigDecimal(DEFAULT_VALUE_亿)) == 1) {
            str=(value.divide(new BigDecimal(DEFAULT_VALUE_亿)).setScale(2,BigDecimal.ROUND_HALF_UP)).toString()+"亿";
        } else{
            str=(value.divide(new BigDecimal(10000)).setScale(2,BigDecimal.ROUND_HALF_UP)).toString()+"万";
        }
        return str;
    }


    /**
     * @param list
     * @return
     */
    private LongHuInfoXiWei getLongHuInfoXiWei(List<LongHuInfoXiWei> list) {
        if (CollectionUtils.isEmpty(list)) {
            return new LongHuInfoXiWei();
        } else {
            return list.get(0);
        }
    }


    private List<LongHuInfoXiWeiEx> dealList(List<LongHuInfoXiWei> xiwei, List<String> buyTag, List<String> saleTag) {
        List<LongHuInfoXiWeiEx> list = Lists.newArrayList();
        xiwei.forEach(item -> {
            LongHuInfoXiWeiEx longHuInfoXiWeiEx = new LongHuInfoXiWeiEx();
            BeanUtils.copyProperties(item, longHuInfoXiWeiEx);
            String yyb = "";
            yyb = getXiWei(item, buyTag, saleTag);
            longHuInfoXiWeiEx.setYyb(getstrKonggeYYB(yyb, 70));
            //查询营业部
            if ("buy".equals(item.getBuyOrSale())) {
                longHuInfoXiWeiEx.setTradeAmount(getstrKonggeYYB(item.getMrje().toString(), 35));
                longHuInfoXiWeiEx.setTradePercent(item.getMrzzcjb().toString() + "%");
            } else {
                longHuInfoXiWeiEx.setTradeAmount(getstrKonggeYYB(item.getMcje().toString(), 35));
                longHuInfoXiWeiEx.setTradePercent(item.getMczcjb().toString() + "%");
            }
            longHuInfoXiWeiEx.setTradeJe(getstrKonggeYYB(item.getJe().toString(), 35));
            yyb = longHuInfoXiWeiEx.getYyb() + longHuInfoXiWeiEx.getTradeAmount() + longHuInfoXiWeiEx.getTradeJe() + longHuInfoXiWeiEx.getTradePercent();
            longHuInfoXiWeiEx.setYyb(yyb);
            list.add(longHuInfoXiWeiEx);
        });
        return list;
    }


    /**
     * 根据营业部查询席位
     * @return
     */
    private String getXiWei(LongHuInfoXiWei xiWei, List<String> buyTag, List<String> saleTag) {
        String yyb = xiWei.getYyb();
        //
        if (StringUtils.isEmpty(yyb)) return "";
        yyb = yyb.replace("股份有限公司", "").replace("证券营业部", "").replace("有限责任公司", "").replace(" ", "");
        Example example = new Example(HotTag.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("hotTemperatureName", yyb.trim());
        List<HotTag> list = hotTagMapper.selectByExample(example);
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(list)) {
            StringBuffer str = new StringBuffer(yyb).append(" (");
            int size = list.size();
            for (int i = 0; i < size; i++) {
                String tag = list.get(i).getHotTag();
                if (xiWei.getBuyOrSale().equals("buy")) {
                    if (!buyTag.contains(tag)) {
                        buyTag.add(tag);
                    }
                } else {
                    if (!saleTag.contains(tag)) {
                        saleTag.add(tag);
                    }
                }
                if ((i == size - 1 && size > 1) || size == 1) {
                    str.append(list.get(i).getHotTag());
                } else {
                    str.append(list.get(i).getHotTag()).append(",");
                }
            }
            str.append(")");
            return str.toString();
        } else {
            return yyb;
        }
    }

    private String getstrKonggeYYB(String string, int num) {
        int size = new BigDecimal(string.length()).multiply(new BigDecimal(1.87)).intValue();
        String buffer =string;
        for (int i = 0; i < num - size; i++) {
            buffer= buffer+"_";
        }
        return buffer;
    }
}
